﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Web;

namespace Api.SuperiorShop
{
    /// <summary>
    /// 生成名片二维码
    /// </summary>
    public class DrawQRImageService
    {
        Font font_name = new Font("PingFangSC-Regular", 32f, FontStyle.Bold, GraphicsUnit.Pixel);
        Color color_Name = ColorTranslator.FromHtml("#000000");

        /// <summary>
        /// 根据二维码分享图片
        /// </summary>
        /// <param name="cardname">名片姓名</param>
        /// <param name="headerimgpath">名片的头像地址</param>
        /// <param name="strbase64">二维码图片base64</param>
        /// <returns>名片分享图片</returns>
        public Bitmap QrCardImage(string cardname, string headerimgpath, string strbase64)
        {
            // 背景图片
            var baseBg = HttpContext.Current.Server.MapPath("~/Content/cardimg/card_x2.png");
            Bitmap bmp = new Bitmap(baseBg);

            //输入名片姓名
            Graphics g = Graphics.FromImage(bmp);
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            g.DrawString(cardname, font_name, new SolidBrush(color_Name), 203, 273);
            g.Dispose();

            var ms = new MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            var imgBase = Image.FromStream(ms);

            // 需要合并的头像 
            var bigmap_header = new Bitmap(headerimgpath);
            //var g1_width = bigmap_header.Width;
            //var g1_height = bigmap_header.Height;
            //var min_g1 = g1_width > g1_height ? g1_height : g1_width;
            //bigmap_header= ResizeImage(bigmap_header, min_g1, min_g1);

            // 图片转成圆角
            Bitmap scmap = WayTwo(bigmap_header);

            // 头像压缩成150px* 150px
            var smallheader = GetThumbnail(scmap, 150, 150);

            // 圆角头像插入到基础图片中
            Bitmap map_header = CombinImage(imgBase, smallheader, 0, -210);

            // base64图片数据 ，实际使用时从缓存取
            byte[] arr = Convert.FromBase64String(strbase64);
            MemoryStream msqr = new MemoryStream(arr);
            Bitmap bmqr = new Bitmap(msqr);

            // 二维码压缩成150px* 150px
            var bmqr192 = GetThumbnail(bmqr, 280, 280);

            // 二维码图片插入到基础图片中
            Bitmap qr_header = CombinImage(map_header, bmqr192, 0, 130);

            GC.Collect();

            return qr_header;
        }

        /// <summary>
        /// 生成产品分享二维码
        /// </summary>
        /// <param name="productname">产品名称</param>
        /// <param name="price">价格</param>
        /// <param name="productimgpath">产品图片</param>
        /// <param name="qrimgbase64">二维码图片base64</param>
        /// <returns>名片分享图片</returns>
        public Bitmap QrProductImage(string productname, string price, string productimgpath, string qrimgbase64)
        {
            // 背景图片
            //var baseBg = HttpContext.Current.Server.MapPath("~/cardimg/product_2x.png");
            //Bitmap bmpbg = new Bitmap(baseBg);
            //var bgImg = ZoomPicture(bmpbg,  315, 554) 
            //Bitmap bmp = new Bitmap(bgImg);
            Bitmap bmp = new Bitmap(1080, 1920);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            g.Dispose();

            // 需要合并的产品
            var bigmap_header = ConvertToStream(productimgpath);
            // 压缩成280px* 280px 
            //var smallProductImg = SizeImageWithOldPercent(bigmap_header, 930, 1240);

            // ZoomPicture(bigmap_header, 1060, 1060);// GetThumbnail(bigmap_header, 310,310);
            //ResizeImage(bigmap_header, 0, 0, 930, 930); //// 320 , :430 
            //SizeImageWithOldPercent(bigmap_header, 930, 930);
            // ResizeImage(bigmap_header, 0, 0, 900, 1200);// 只有截取功能
            // ZoomPicture(bigmap_header, 930, 930);
            var srcwidth = bigmap_header.Width;
            var srcheight = bigmap_header.Height;
            var tgWidth = 930;
            var tgHeight = 1240;
            int inwidth = 0;
            int inheight = 0;

            if (tgWidth / tgHeight >= srcwidth / srcheight)
            {
                inwidth = srcwidth;
                inheight = tgHeight * inwidth / tgWidth;
            }
            else
            {
                inheight = srcheight;
                inwidth = tgWidth * inheight / tgHeight;
            }
            //var imgTg1  =  ResizeImage(bigmap_header, 0, 0, inwidth, inheight);// 只有截取功能
            // Image  imgTg1 = ResizeImage(bigmap_header,0,0,inwidth, inheight);// 只有截取功能
            Image imgTg1 = GetThumbnail(bigmap_header, inheight, inwidth);
            if (imgTg1 == null)
            {
                imgTg1 = bigmap_header;
            }
            //缩放
            Bitmap srcmap = new Bitmap(imgTg1, imgTg1.Width, imgTg1.Height);
            var smallProductImg = SizeImageWithOldPercent(srcmap, tgWidth, tgHeight);


            // 图片插入到基础图片中
            bmp = CombinImage(bmp, smallProductImg, 0, -270);

            // base64图片 二维码数据
            byte[] arr = Convert.FromBase64String(qrimgbase64);
            MemoryStream msqr = new MemoryStream(arr);
            Bitmap bmqr = new Bitmap(msqr);
            var bmp275 = ResizeImage(bmqr, 0, 0, 275, 275);
            // 282, 321
            // 二维码压缩成150px* 150px
            //var bmqr90_90 = ZoomPicture(bmqr, 210, 224);
            //bmqr90_90 = ResizeImage(bmqr90_90, 0, 0, 210, 202);
            // 二维码图片插入到基础图片中
            bmp = CombinImage(bmp, bmp275, 330, 625);

            g = Graphics.FromImage(bmp);
            //  Graphics.TextRenderingHint...注意一点,修改TextRenderingHint的话,需要引入System.Drawing.Text,例如:
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

            //产品名称
            Font font_productname = new Font("PingFang SC Regular", 54f, FontStyle.Regular, GraphicsUnit.Pixel);
            Color color_productname = ColorTranslator.FromHtml("#333333");
            // Graphics g = Graphics.FromImage(qr_header);  
            g.DrawString(productname, font_productname, new SolidBrush(color_productname), 60, 430 * 3.43f); // 1108, 130 +  110 
            //产品价格
            // Font  PingFangSC-Regular PingFangSC-Regular
            Font font_price = new Font("PingFang SC Regular", 66f, FontStyle.Regular, GraphicsUnit.Pixel);
            Color color_price = ColorTranslator.FromHtml("#FA4B44");
            g.DrawString(price, font_price, new SolidBrush(color_price), 55, 465 * 3.43f);

            Font font_sc = new Font("PingFang SC Regular", 28f, FontStyle.Regular, GraphicsUnit.Pixel);
            Color color_sc = ColorTranslator.FromHtml("#333333");
            g.DrawString("扫描或长按小程序码", font_sc, new SolidBrush(color_sc), 740, 1724);

            g.Dispose();

            //var ms = new MemoryStream();
            //qr_header.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            //var imgBase = Image.FromStream(ms);

            bmp = GetThumbnail(bmp, 960, 540);

            GC.Collect();
            return bmp;
        }

#pragma warning disable CS1573 // 参数“yDeviation”在“MobileCardQRImageService.CombinImage(Image, Image, int, int)”的 XML 注释中没有匹配的 param 标记(但其他参数有)
#pragma warning disable CS1573 // 参数“xDeviation”在“MobileCardQRImageService.CombinImage(Image, Image, int, int)”的 XML 注释中没有匹配的 param 标记(但其他参数有)
        /// <summary>  
        /// 合并图片  
        /// </summary>  
        /// <param name="imgBack"></param>  
        /// <param name="img"></param>  
        /// <returns></returns>  
        public static Bitmap CombinImage(Image imgBack, Image img, int xDeviation = 0, int yDeviation = 0)
#pragma warning restore CS1573 // 参数“xDeviation”在“MobileCardQRImageService.CombinImage(Image, Image, int, int)”的 XML 注释中没有匹配的 param 标记(但其他参数有)
#pragma warning restore CS1573 // 参数“yDeviation”在“MobileCardQRImageService.CombinImage(Image, Image, int, int)”的 XML 注释中没有匹配的 param 标记(但其他参数有)
        {
            Bitmap bmp = new Bitmap(imgBack.Width, imgBack.Height);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);
            //白色边框
            // g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 + xDeviation - 1, imgBack.Height / 2 - img.Height / 2 + yDeviation - 1, img.Width + 2, img.Height + 2);
            //填充图片
            g.DrawImage(img, imgBack.Width / 2 - img.Width / 2 + xDeviation, imgBack.Height / 2 - img.Height / 2 + yDeviation, img.Width, img.Height);
            GC.Collect();
            return bmp;
        }

        /// <summary>  
        /// Resize图片  
        /// </summary>  
        /// <param name="bmp">原始Bitmap</param>  
        /// <param name="newW">新的宽度</param>  
        /// <param name="newH">新的高度</param>  
        /// <returns>处理以后的图片</returns>  
        public static Bitmap ResizeImage(Image bmp, int newW, int newH)
        {
            try
            {
                Bitmap b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);
                // 插值算法的质量    
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height),
                            GraphicsUnit.Pixel);
                g.Dispose();
                return b;
            }
            catch
            {
                return null;
            }
        }

        #region 从大图中截取一部分图片
        /// <summary>
        /// 从大图中截取一部分图片
        /// </summary>
        /// <param name="fromImage">来源图片</param>        
        /// <param name="offsetX">从偏移X坐标位置开始截取</param>
        /// <param name="offsetY">从偏移Y坐标位置开始截取</param>
        /// <param name="width">保存图片的宽度</param>
        /// <param name="height">保存图片的高度</param>
        /// <returns></returns>
        public Image ResizeImage(Image fromImage, int offsetX, int offsetY, int width, int height)
        {
            //创建新图位图
            Bitmap bitmap = new Bitmap(width, height);
            //创建作图区域
            Graphics graphic = Graphics.FromImage(bitmap);
            //截取原图相应区域写入作图区
            graphic.DrawImage(fromImage, 0, 0, new Rectangle(offsetX, offsetY, width, height), GraphicsUnit.Pixel);
            //从作图区生成新图
            Image saveImage = Image.FromHbitmap(bitmap.GetHbitmap());
            ////保存图片
            //saveImage.Save(toImagePath, ImageFormat.Png);
            ////释放资源   
            //saveImage.Dispose();
            //graphic.Dispose();
            //bitmap.Dispose();
            return saveImage;
        }
        #endregion

        /// <summary>
        /// 图片压缩到指定宽度和高度
        /// </summary>
        /// <param name="b"></param>
        /// <param name="destHeight"></param>
        /// <param name="destWidth"></param>
        /// <returns></returns>
        public static Bitmap GetThumbnail(Bitmap b, int destHeight, int destWidth)
        {
            System.Drawing.Image imgSource = b;
            System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat;
            int sW = 0, sH = 0;
            // 按比例缩放           
            int sWidth = imgSource.Width;
            int sHeight = imgSource.Height;
            if (sHeight > destHeight || sWidth > destWidth)
            {
                if ((sWidth * destHeight) > (sHeight * destWidth))
                {
                    sW = destWidth;
                    sH = (destWidth * sHeight) / sWidth;
                }
                else
                {
                    sH = destHeight;
                    sW = (sWidth * destHeight) / sHeight;
                }
            }
            else
            {
                return b;
#pragma warning disable CS0162 // 检测到无法访问的代码
                sW = sWidth;
#pragma warning restore CS0162 // 检测到无法访问的代码
                sH = sHeight;
            }

            Bitmap outBmp = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage(outBmp);
            g.Clear(Color.Transparent);
            // 设置画布的描绘质量         
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(imgSource, new Rectangle((destWidth - sW) / 2, (destHeight - sH) / 2, sW, sH), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            // 以下代码为保存图片时，设置压缩质量     
            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;
            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;
            imgSource.Dispose();
            return outBmp;
        }

#pragma warning disable CS1572 // XML 注释中有“file”的 param 标记，但是没有该名称的参数
#pragma warning disable CS1573 // 参数“bitmap”在“MobileCardQRImageService.WayOne(Bitmap)”的 XML 注释中没有匹配的 param 标记(但其他参数有)
        /// <summary>
        /// 图片转成圆角方法一
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private Bitmap WayOne(Bitmap bitmap)
#pragma warning restore CS1573 // 参数“bitmap”在“MobileCardQRImageService.WayOne(Bitmap)”的 XML 注释中没有匹配的 param 标记(但其他参数有)
#pragma warning restore CS1572 // XML 注释中有“file”的 param 标记，但是没有该名称的参数
        {
            //using (Image i = new Bitmap(file))
            using (Image i = bitmap)
            {
                Bitmap b = new Bitmap(i.Width, i.Height);
                using (Graphics g = Graphics.FromImage(b))
                {
                    g.FillEllipse(new TextureBrush(i), 0, 0, i.Width, i.Height);
                }
                return b;
            }
        }
        /// <summary>
        /// 图片转成圆角方法二
        /// </summary>
        private Bitmap WayTwo(Bitmap bitmap)
        {
            //using (Image i = new Bitmap(file))
            using (Image i = bitmap)
            {
                Bitmap b = new Bitmap(i.Width, i.Height);
                using (Graphics g = Graphics.FromImage(b))
                {
                    g.DrawImage(i, 0, 0, b.Width, b.Height);
                    int r = Math.Min(b.Width, b.Height) / 2;
                    PointF c = new PointF(b.Width / 2.0F, b.Height / 2.0F);
                    for (int h = 0; h < b.Height; h++)
                        for (int w = 0; w < b.Width; w++)
                            if ((int)Math.Pow(r, 2) < ((int)Math.Pow(w * 1.0 - c.X, 2) + (int)Math.Pow(h * 1.0 - c.Y, 2)))
                            {
                                b.SetPixel(w, h, Color.Transparent);
                            }
                }
                return b;
            }
        }
        // private Bitmap WaySOne(string file)

        /// <summary>
        /// 图片转成圆角方法三
        /// </summary>
        private Bitmap WaySOne(Bitmap bitmap)
        {
            // using (Image i = new Bitmap(file))
            using (Image i = bitmap)
            {
                Bitmap b = new Bitmap(i.Width, i.Height);
                using (Graphics g = Graphics.FromImage(b))
                {
                    g.Clear(Color.White);
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    using (System.Drawing.Drawing2D.GraphicsPath p = new System.Drawing.Drawing2D.GraphicsPath(System.Drawing.Drawing2D.FillMode.Alternate))
                    {
                        p.AddEllipse(0, 0, i.Width, i.Height);
                        g.FillPath(new TextureBrush(i), p);
                    }
                    g.FillEllipse(new TextureBrush(i), 0, 0, i.Width, i.Height);

                    g.Clear(Color.White);
                }
                return b;
            }
        }

        /// <summary>
        /// 图片转成圆角方法四
        /// </summary>
        private Bitmap WaySTwo(string file)
        {
            using (Image i = new Bitmap(file))
            {
                Bitmap b = new Bitmap(i.Width, i.Height);
                using (Graphics g = Graphics.FromImage(b))
                {
                    g.DrawImage(i, 0, 0, b.Width, b.Height);
                    int r = Math.Min(b.Width, b.Height) / 2;
                    PointF c = new PointF(b.Width / 2.0F, b.Height / 2.0F);
                    for (int h = 0; h < b.Height; h++)
                        for (int w = 0; w < b.Width; w++)
                            if ((int)Math.Pow(r, 2) < ((int)Math.Pow(w * 1.0 - c.X, 2) + (int)Math.Pow(h * 1.0 - c.Y, 2)))
                            {
                                b.SetPixel(w, h, Color.Transparent);
                            }
                    //画背景色圆
                    using (Pen p = new Pen(System.Drawing.SystemColors.Control))
                        g.DrawEllipse(p, 0, 0, b.Width, b.Height);
                }
                return b;
            }
        }
        /// <summary>
        /// 图片转为base64编码的字符串
        /// </summary>
        /// <param name="Imagefilename"></param>
        /// <returns></returns>
        protected string ImgToBase64String(string Imagefilename)
        {
            try
            {
                Bitmap bmp = new Bitmap(Imagefilename);

                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
#pragma warning disable CS0168 // 声明了变量“ex”，但从未使用过
            catch (Exception ex)
#pragma warning restore CS0168 // 声明了变量“ex”，但从未使用过
            {
                return null;
            }
        }

        /// <summary>
        /// threeebase64编码的字符串转为图片
        /// </summary>
        /// <param name="strbase64"></param>
        /// <returns></returns>
        protected Bitmap Base64StringToImage(string strbase64)
        {
            try
            {
                byte[] arr = Convert.FromBase64String(strbase64);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);

                bmp.Save(@"d:\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                //bmp.Save(@"d:\"test.bmp", ImageFormat.Bmp);
                //bmp.Save(@"d:\"test.gif", ImageFormat.Gif);
                //bmp.Save(@"d:\"test.png", ImageFormat.Png);
                ms.Close();
                return bmp;
            }
#pragma warning disable CS0168 // 声明了变量“ex”，但从未使用过
            catch (Exception ex)
#pragma warning restore CS0168 // 声明了变量“ex”，但从未使用过
            {
                return null;
            }
        }

        // 按比例缩放图片
#pragma warning disable CS1591 // 缺少对公共可见类型或成员“MobileCardQRImageService.ZoomPicture(Image, int, int)”的 XML 注释
        public Bitmap ZoomPicture(Image SourceImage, int TargetWidth, int TargetHeight)
#pragma warning restore CS1591 // 缺少对公共可见类型或成员“MobileCardQRImageService.ZoomPicture(Image, int, int)”的 XML 注释
        {
            int IntWidth; //新的图片宽
            int IntHeight; //新的图片高
            try
            {
                System.Drawing.Imaging.ImageFormat format = SourceImage.RawFormat;
                System.Drawing.Bitmap SaveImage = new System.Drawing.Bitmap(TargetWidth, TargetHeight);
                Graphics g = Graphics.FromImage(SaveImage);
                g.Clear(Color.White);

                //计算缩放图片的大小 http://www.cnblogs.com/roucheng/
                // https://www.cnblogs.com/roucheng/p/3509606.html
                if (SourceImage.Width > TargetWidth && SourceImage.Height <= TargetHeight)//宽度比目的图片宽度大，长度比目的图片长度小
                {
                    IntWidth = TargetWidth;
                    IntHeight = (IntWidth * SourceImage.Height) / SourceImage.Width;
                }
                else if (SourceImage.Width <= TargetWidth && SourceImage.Height > TargetHeight)//宽度比目的图片宽度小，长度比目的图片长度大
                {
                    IntHeight = TargetHeight;
                    IntWidth = (IntHeight * SourceImage.Width) / SourceImage.Height;
                }
                else if (SourceImage.Width <= TargetWidth && SourceImage.Height <= TargetHeight) //长宽比目的图片长宽都小
                {
                    IntHeight = SourceImage.Width;
                    IntWidth = SourceImage.Height;
                }
                else//长宽比目的图片的长宽都大
                {
                    IntWidth = TargetWidth;
                    IntHeight = (IntWidth * SourceImage.Height) / SourceImage.Width;
                    if (IntHeight > TargetHeight)//重新计算
                    {
                        IntHeight = TargetHeight;
                        IntWidth = (IntHeight * SourceImage.Width) / SourceImage.Height;
                    }
                }

                g.DrawImage(SourceImage, (TargetWidth - IntWidth) / 2, (TargetHeight - IntHeight) / 2, IntWidth, IntHeight);
                SourceImage.Dispose();

                return SaveImage;
            }
#pragma warning disable CS0168 // 声明了变量“ex”，但从未使用过
            catch (Exception ex)
#pragma warning restore CS0168 // 声明了变量“ex”，但从未使用过
            {

            }

            return null;
        }


        /// <summary> 
        /// 按照指定大小缩放图片，但是为了保证图片宽高比自动截取 
        /// </summary> 
        /// <param name="srcPath">原图片路径</param> 
        /// <param name="destWidth">目标图片宽</param> 
        /// <param name="destHeight">目标图片高</param> 
        /// <returns></returns> 
        public static Bitmap SizeImageWithOldPercent(Bitmap srcPath, int destWidth, int destHeight)
        {
            Image srcImage = srcPath;
            try
            {
                // 要截取图片的宽度（原始宽度） 
                int srcWidth = srcImage.Width;
                // 要截取图片的高度（原始高度） 
                int srcHeight = srcImage.Height;
                // 截取开始横坐标
                int newX = 0;
                // 截取开始纵坐标 
                int newY = 0;

                // 截取比例 
                double whPercent = ((double)destWidth / (double)destHeight) * ((double)srcImage.Height / (double)srcImage.Width);
                if (whPercent > 1)
                {
                    // 当前图片宽度对于要截取比例过大时 
                    srcWidth = int.Parse(Math.Round(srcImage.Width / whPercent).ToString());
                }
                else if (whPercent < 1)
                {
                    // 当前图片高度对于要截取比例过大时 
                    srcHeight = int.Parse(Math.Round(srcImage.Height * whPercent).ToString());
                }

                if (srcWidth != srcImage.Width)
                {
                    // 宽度有变化时，调整开始截取的横坐标 
                    newX = Math.Abs(int.Parse(Math.Round(((double)srcImage.Width - srcWidth) / 2).ToString()));
                }
                else if (srcHeight == srcImage.Height)
                {
                    // 高度有变化时，调整开始截取的纵坐标 
                    newY = Math.Abs(int.Parse(Math.Round(((double)srcImage.Height - (double)srcHeight) / 2).ToString()));
                }

                // 将原始图片画到目标画布上，返回目标图片
                Bitmap cutedImage = CutImage(srcImage, newX, newY, srcWidth, srcHeight);

                // 在创建一个新的画布
                Bitmap bmp = new Bitmap(destWidth, destHeight);
                Graphics g = Graphics.FromImage(bmp);
                // 插值算法的质量 
                g.InterpolationMode = InterpolationMode.Default;
                g.DrawImage(cutedImage, new Rectangle(0, 0, destWidth, destHeight), new Rectangle(0, 0, cutedImage.Width, cutedImage.Height), GraphicsUnit.Pixel);
                g.Dispose();

                return bmp;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary> 
        /// 剪裁 -- 用GDI+ 
        /// </summary> 
        /// <param name="image">原始图片</param> 
        /// <param name="StartX">开始坐标X</param> 
        /// <param name="StartY">开始坐标Y</param> 
        /// <param name="destWidth">目标图片宽度</param> 
        /// <param name="destHeight">目标图片高度高度</param> 
        /// <returns>剪裁后的Bitmap</returns> 
        public static Bitmap CutImage(Image image, int StartX, int StartY, int destWidth, int destHeight)
        {
            int srcWidth = image.Width;
            int srcHeight = image.Height;
            if (StartX >= srcWidth || StartY >= srcHeight)
            {
                // 开始截取坐标过大时，结束处理 
                return null;
            }

            if (StartX + destWidth > srcWidth)
            {
                // 宽度过大时只截取到最大大小 
                destWidth = srcWidth - StartX;
            }

            if (StartY + destHeight > srcHeight)
            {
                // 高度过大时只截取到最大大小 
                destHeight = srcHeight - StartY;
            }

            try
            {
                // 根据目标图片的大小，实例化一个画布
                Bitmap bmpOut = new Bitmap(destWidth, destHeight);
                // 实例化一个画笔
                Graphics g = Graphics.FromImage(bmpOut);
                // 将原始图片画到目标画布上
                g.DrawImage(image, new Rectangle(0, 0, destWidth, destHeight), new Rectangle(StartX, StartY, destWidth, destHeight), GraphicsUnit.Pixel);
                g.Dispose();

                return bmpOut;
            }
            catch
            {
                return null;
            }

        }
        /// <summary>
        /// 将URL格式的图片转bitmap
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static Bitmap ConvertToStream(string picUrl)
        {
            WebRequest webreq = WebRequest.Create(picUrl);
            WebResponse webres = webreq.GetResponse();
            Bitmap res = null;
            using (Stream stream = webres.GetResponseStream())
            {
                res = new Bitmap(stream) ;

            }
            return res;
      
        }

    }
}
